#include <RenderSubsystem/cvImmediateModeRenderer.h>
#include <RenderSubSystem/cvIMRenderer/IMCameraObject.h>
#include <RenderSubSystem/cvIMRenderer/Line.h>
#include <RenderSubSystem/cvIMRenderer/LinePrimitiveMemoryManager.h>
#include <gl/GLFW.h>
namespace cvImmediateModeRenderer
{
	ImmediateModeRenderer::ImmediateModeRenderer()
	{
		m_activelayer = &m_dummylayer;
		m_activecamera = static_cast<cvObjects::BaseCameraObject*>(IMCameraObject::create());

		/** CONFIGURE THE RENDERER */
	}


	ImmediateModeRenderer::~ImmediateModeRenderer()
	{
		LOGDEBUG("ImmediateModeRenderer:: freeing resources..");

		// Free camera objects..
		m_activecamera->destroy();
		m_activecamera = 0;
		// free renderables.
		/*for(renderable_list_t::iterator it = m_renderinglist.begin(); it != m_renderinglist.end(); it++)
		{
			(*it)->destroy();
		}
		// dump pools
		boost::singleton_pool<boost::pool_allocator_tag, sizeof(line_struct_vert)>::purge_memory();
		boost::singleton_pool<boost::pool_allocator_tag, sizeof(line_struct_color)>::purge_memory();
		boost::singleton_pool<boost::fast_pool_allocator_tag, sizeof(Line*)>::purge_memory();*/
	}

	void ImmediateModeRenderer::setScene( cvRenderInterface::Renderinglayer * layer )
	{
		m_activelayer = layer;
		LOGDEBUG("::RENDERER() !SWITCHED RENDRING LAYER!");
	}

	void ImmediateModeRenderer::setActiveCamera(cvObjects::BaseCameraObject * cam)
	{
		m_activecamera = cam;
		LOGDEBUG("::RENDERER() !SWITCHED ACTIVE CAMERA!");
	}


	void ImmediateModeRenderer::render()
	{
		//#1 Update
		//#2 Primitive Node allocator
		//#3 Z-Sort-Group-Sort
		//#4 Rendering list managment
		//#5 Collection by visibility
		//#6 Node Transport
		//#7 Rendering

		//(update objects)
		m_activelayer->processZSort();			//#3 Z-Sort
		m_activelayer->processCollections();	//#4 Rendering list managment

		m_activecamera->update();				// CAMERA
		m_activecamera->setup();

		glClearColor(ClsColour.r, ClsColour.g, ClsColour.b,ClsColour.a);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


		/// RENDER
		for(cvRenderInterface::renderinglist_t::iterator it = m_activelayer->renderList.begin(); it != m_activelayer->renderList.end(); ++it)
		{
			it->processCollect(m_activecamera);	//#5 Collection by visibility
			it->processTransfer();				//#6 Node Transport
			it->processRender();				//#7 Rendering
		}

		glFinish();
		/// Flush singleshot CollectionNodes.
		//flush_singleshots();
	}

	cvRenderInterface::RenderableLine * ImmediateModeRenderer::createLine()	{ return Line::create(); }
};
